import 'package:dio/dio.dart';
import 'package:example/utils/common.dart';

/// 自定义异常
class HttpRespException implements Exception {
  final String message;
  final int code;

  HttpRespException(this.code, this.message);

  String toString() => "code:$code \n message:$message";

  factory HttpRespException.init(DioException error) {
    switch (error.type) {
      case DioExceptionType.cancel:
        return HttpRespException(-1, "请求取消");
      case DioExceptionType.connectionTimeout:
        return HttpRespException(-1, "连接超时");
      case DioExceptionType.sendTimeout:
        return HttpRespException(-1, "请求超时");
      case DioExceptionType.receiveTimeout:
        return HttpRespException(-1, "响应超时");
      case DioExceptionType.unknown:
        if((error.message ?? '').contains("SocketException: Failed host lookup")) {
          return HttpRespException(-1, "网络异常");
        }else{
          logger.e("HttpRespException -> ${error.toString()}");
          return HttpRespException(-1, error.message ?? '');
        }
      case DioExceptionType.badResponse:
        int errCode = error.response?.statusCode ?? -1;
        dynamic errMsg = error.response?.data;
        try {
          if (error.response?.data is String) {
            errMsg = error.response?.data;
          } else {
            errMsg = error.response?.data["msg"];
          }
        } catch (e) {
          logger.e("DioErrorType.response:$e");
        }
        if (isNotEmptyOrNull(errMsg)) {
          return HttpRespException(errCode, errMsg);
        }
        switch (errCode) {
          case 201:
            return HttpRespException(errCode, "状态变更无法进行操作");
          case 400:
            return HttpRespException(errCode, "请求语法错误");
          case 401:
            return HttpRespException(errCode, "认证过期");
          case 402:
            return HttpRespException(errCode, "请重新登录");
          case 403:
            return HttpRespException(errCode, "服务器拒绝执行");
          case 404:
            return HttpRespException(errCode, "无法连接服务器");
          case 405:
            return HttpRespException(errCode, "请求方法被禁止");
          case 500:
            return HttpRespException(errCode, "服务器内部错误");
          case 502:
            return HttpRespException(errCode, "无效的请求");
          case 503:
            return HttpRespException(errCode, "服务器内部错误");
          case 505:
            return HttpRespException(errCode, "不支持HTTP协议请求");
          default:
            logger.e("HttpRespException -> ${error.toString()}");
            return HttpRespException(
                errCode, error.response?.statusMessage ?? '未知错误');
        }
      default:
        logger.e("HttpRespException -> ${error.toString()}");
        return HttpRespException(-1, error.message ?? '');
    }
  }
}
